package com.zqx.tokenauth.service.impl;

import com.zqx.tokenauth.entity.TokenModel;
import com.zqx.tokenauth.enums.TokenEnum;
import com.zqx.tokenauth.service.TokenManager;
import com.zqx.tokenauth.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * title:通过Redis存储和验证token的实现类
 * @author zqx
 * @date 2018.07.21
 */
@Component
public class RedisTokenManager implements TokenManager {


    private RedisTemplate<Object, Object> redis;

    @Autowired
    public void setRedis(RedisTemplate<Object, Object> redis)
    {
        this.redis = redis;
        redis.setKeySerializer(new JdkSerializationRedisSerializer());
    }

    /**
     * 生成token
     * @param userId 指定用户的 id
     * @return
     */
    @Override
    public TokenModel createToken(long userId) {

        //使用uuid生成token
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenModel model = new TokenModel(userId, token);
        redis.boundValueOps(userId).set(token, TokenEnum.TOKEN_EXPIRES_HOUR.getCode(), TimeUnit.HOURS);
        return model;
    }

    @Override
    public boolean checkToken(TokenModel model) {
        if(model == null)
        {
            return false;
        }
        String token = (String)redis.boundValueOps(model.getUserId()).get();
        if(token == null || !token.equals (model.getToken ()))
        {
            return false;
        }

        // 如果验证成功，说明此用户进行了一次有效操作，延长 token 的过期时间
        redis.boundValueOps(model.getUserId()).expire(TokenEnum.TOKEN_EXPIRES_HOUR.getCode(),TimeUnit.HOURS);
        return true;
    }

    /**
     * 从字符串中解析 token
     * @param authentication 加密后的字符串
     * @return
     */
    @Override
    public TokenModel getToken(String authentication) {
        if(authentication == null || authentication.length () == 0)
        {
            return null;
        }
        String[] param = authentication.split("_");
        if(param.length !=2)
        {
            return null;
        }
        // 使用 userId 和源 token 简单拼接成的 token，可以增加加密措施
        long userId = Long.parseLong (param [0]);
        String token = param [1];
        return new TokenModel(userId,token);
    }

    @Override
    public void deleteToken(long userId) {
        redis.delete(userId);
    }
}
